package com.ruoyi.business.api;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.business.config.MqttConfig;
import com.ruoyi.business.interceptor.MqttPushClient;
import com.ruoyi.business.websocket.WebSocketServer;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sign.AESUtils;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @author JerryLu
 * @date 2024/8/4 17:15
 * @description 地磅接口
 */
@Component
@Slf4j
public class WeighBridgeApi {

    private RestTemplate restTemplate;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private MqttConfig mqttConfig;

    @Autowired
    private MqttPushClient mqttPushClient;

    public R send(JSONObject jsonObject) throws MqttException {
        String topic = mqttConfig.getTopicSend();
        topic = topic.replace("+", jsonObject.getString("billno"));
        mqttPushClient.publish(false, topic, jsonObject.toJSONString());
        return R.ok();
    }

    public void disposeBusiness(String topic, String _msg) {
        try {
            if (StringUtils.isNotEmpty(_msg)) {
                if (topic.matches("hz/receive/.+/response")) {
                    JSONObject json = JSON.parseObject(_msg);
                    JSONObject jsonObject = JSON.parseObject(json.getString("data"));
                    if (jsonObject.getInteger("type") == 1) {
                        log.info("收到收货毛重称重消息：{}", _msg);
                    } else if (jsonObject.getInteger("type") == 2) {
                        log.info("收到收货皮重称重消息：{}", _msg);
                    } else if (jsonObject.getInteger("type") == 3) {
                        log.info("收到发货毛重称重消息：{}", _msg);
                    } else if (jsonObject.getInteger("type") == 4) {
                        log.info("收到发货皮重称重消息：{}", _msg);
                    }
                    // 主动向前端发送地磅称重数据
                    webSocketServer.sendMessage(jsonObject.toString());
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
